package com.cskt.petgateway.filter;

import com.fasterxml.jackson.databind.JsonNode;
import jakarta.servlet.ServletException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.servlet.function.ServerRequest;

import java.io.IOException;
import java.util.Optional;
import java.util.function.Function;

/**
 * @author admin
 **/

public class BeforeFilterFunctions {

    private static final Logger log = LoggerFactory.getLogger(BeforeFilterFunctions.class);

    public static Function<ServerRequest, ServerRequest> instrument() {
        return new Function<ServerRequest, ServerRequest>() {
            @Override
            public ServerRequest apply(ServerRequest request) {
                StringBuffer stringBuffer = new StringBuffer();

                MediaType mediaType = request.headers().contentType().get();

                if (mediaType.equals(MediaType.APPLICATION_JSON_VALUE)) {
                    //请求参数在body中
                    try {
                        String body = request.body(String.class);
                        log.info("请求参数：{}", body);
                    } catch (ServletException | IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    //request.at
                    MultiValueMap<String, String> params = request.params();
                    params.keySet().forEach(key -> {
                        stringBuffer.append("{")
                                .append(key)
                                .append("=")
                                .append(params.get(key))
                                .append(",");
                    });
                } 
                return ServerRequest.from(request).build();
            }
        };
    }

}
